package com.ltliguo.controller;

import com.ltliguo.domain.Goods;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/consumer")
public class ConsumerController {
    @Autowired
    //模拟访问
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    /*//根据商品id调用商品信息
    @GetMapping("/findGoodsById/{id}")
    public Goods findGoodsById(@PathVariable Integer id){
        System.out.println("findGoodsById..."+id);

        //调用provider服务中的接口
        //String url="http://localhost:8080/provider/findOne/"+id;
        //利用restTemplate模板模拟浏览器发请求
        //Goods goods = restTemplate.getForObject(url, Goods.class);

        //从eureka服务列表中获取客户端服务列表，参数表示的是服务id
        List<ServiceInstance> instanceList = discoveryClient.getInstances("CLOUD-PROVIDER");

        ServiceInstance serviceInstance = instanceList.get(0);

        int port = serviceInstance.getPort();

        String host = serviceInstance.getHost();

        String instanceId = serviceInstance.getInstanceId();

        System.out.println("port="+port+", host="+host+", instanceId="+instanceId);

        String url="http://"+host+":"+port+"/provider/findOne/"+id;

        Goods goods = restTemplate.getForObject(url, Goods.class);

        return goods;

    }*/

    @GetMapping("/findGoodsById2/{id}")
    public Goods findGoodsById2(@PathVariable int id){
        System.out.println("findGoodsById2..."+id);
        //调用provider服务中的接口，形式http://注册中心服务id/provider/findOne/{id}
        String url="http://cloud-provider/provider/findOne/"+id;
        Goods goods=restTemplate.getForObject(url,Goods.class);
        return goods;
    }
}
